--[[ 战国之刃脚本,边缘参考线形式(坐标如此),power监视
  测试发现,实际体积大概需要在坐标的右边缘+3
  
  By setycyas @2025-02-19
]]

--防止重运行,需用用_G,用重复require不行,因为F4重启可能会把脚本加载到全新模块与原来的不共通
if (_G.game) then
  print('script already loaded!')
  return
end

local myMame = require('MyMame')
local myStg = require('MySTG')

-- 这里设定基本参数
local GAME = {
  -- 脚本名,显示识别运行等使用
  NAME = "tengai_autoboot",
  -- 分辨率
  X_RESOLUTION = 320.0,
  Y_RESOLUTION = 224.0,
  -- 边缘坐标,全部用read_u16
  YUP_ADDR = 0x00fe3480,
  XLEFT_ADDR = 0x00fe3482,
  YDOWN_ADDR = 0x00fe3484,
  XRIGHT_ADDR = 0x00fe3486,
  -- 偏移修正
  XRIGHT_OFFSET = 3,
  -- 火力地址
  POW_ADDR = 0x00fe3497,
  -- 边缘参考线的宽度,颜色
  SIDE_LINE_WIDTH = 1,
  SIDE_LINE_COLOR = 0xDDffd700,
  -- 中途需要变更的测试参数,准备了10个
  TEST_PARAMS = {3, 0x000c60e1, 0, 30, 15, 0.0, 0.0, 0.0, 0.0, 0.0},
  -- 调用模块
  myMame = myMame,
  myStg = myStg,
}
-- 更新模块设置
-- 更新一下模块的参数
myMame.gameName = GAME.NAME
myMame.screenIndex = ':screen'
myStg.screenIndex = ':screen'
myStg.X_RESOLUTION = GAME.X_RESOLUTION
myStg.Y_RESOLUTION = GAME.Y_RESOLUTION

-- 监视各地址,测试时用投入使用时不显示
function GAME.watchAddrs()
  local addrArr, i
  addrArr = {
  }
  for i = 1, 0x10 do
    addrArr[i] = 0x00fe347b+i
  end
  strArr = myMame.readAddrArr(addrArr)
  myMame.showInfo(strArr)
end

-- 显示监视的数据
function GAME.check()
  local power, str
  power = myMame.mem:read_u8(GAME.POW_ADDR)
  
  str = string.format(" P = %d ", power)
  myMame.container:draw_text(0.02, 0.965, str, 0xFF005500, 0xFFcccccc)
end

-- 获取坐标,各返回两个整数表示两边
function GAME.getX()
  return myMame.mem:read_u16(GAME.XLEFT_ADDR), myMame.mem:read_u16(GAME.XRIGHT_ADDR)+GAME.XRIGHT_OFFSET
end
function GAME.getY()
  return myMame.mem:read_u16(GAME.YUP_ADDR), myMame.mem:read_u16(GAME.YDOWN_ADDR)
end

-- 显示边缘参考线
function GAME.sideLines(xleft, xright, ydown, yup)
  
  -- 需要终止显示的情况
  if (xleft == 0) or (xright == 0) or (ydown == 0) or (yup == 0) then
    return
  end
  if (math.abs(xleft-xright) > 50) or (math.abs(ydown-yup) > 50) then
    return
  end
  
  -- 画边缘参考线
  myStg.xLine(xleft, GAME.SIDE_LINE_COLOR, GAME.SIDE_LINE_WIDTH)
  myStg.xLine(xright, GAME.SIDE_LINE_COLOR, GAME.SIDE_LINE_WIDTH)
  myStg.yLine(ydown, GAME.SIDE_LINE_COLOR, GAME.SIDE_LINE_WIDTH)
  myStg.yLine(yup, GAME.SIDE_LINE_COLOR, GAME.SIDE_LINE_WIDTH)
  
end

-- 主函数,绑定后每一帧执行一次该函数
function GAME.Main() 
  local xleft, xright, ydown, yup
  xleft, xright = GAME.getX()
  ydown, yup = GAME.getY()
  
  -- 监视地址
  --GAME.watchAddrs()
  -- 显示数据监视
  GAME.check()
  -- 边缘参考线
  GAME.sideLines(xleft, xright, ydown, yup)
  
end

-- [[运行]]

-- 导出到全局变量
_G.game = GAME
-- 绑定每一帧执行的函数,测试时绑定到debug
--myMame.debugRunPerFrame(GAME.Main, 'tengai')
myMame.runPerFrame(GAME.Main, 'tengai')

return GAME
